package com.five.controller;

import com.five.entity.Chapter;
import com.five.exceptions.BusinessException;
import com.five.util.StringUtil;
import com.five.vo.BaseResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("upload")
@Api(tags = "文件上传相关业务")
@CrossOrigin
public class UploadController extends BaseController{

    //图片保存位置(tomcat)
    private String UploadImgRelativePath="E:\\install\\apache-tomcat-9.0.40\\webapps\\view\\img\\";
    //视频保存位置(tomcat)
    private String UploadVideoRelativePath="E:\\install\\apache-tomcat-9.0.40\\webapps\\video\\";
    //分片上传视频保存路径
    @Value("${five.upload.video.path}")
    private String decryptFilePath;
    //临时文件保存路径
    @Value("${five.upload.video.temp}")
    private String decryptFilePathTemp;

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST
            , headers = "content-type=multipart/form-data"
            , consumes = "multipart/*")
    @ApiOperation("文件上传接口")
    @ResponseBody
    public BaseResultVO upload(MultipartFile file){
        //组合保存地址
        String dateDir = StringUtil.getUploadDateDir();
        String uploadPath = "";
        System.out.println(file);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(suffix.equalsIgnoreCase("mp4")){
            uploadPath = UploadImgRelativePath;
        } else{
            uploadPath = UploadImgRelativePath;
        }
        File dirFile = new File(uploadPath +dateDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String fileName = StringUtil.getTimeStampString()+"-"+file.getOriginalFilename();
        String filePath = dateDir+fileName;

        try {
            //读取文件保存到具体目录中
            file.transferTo(new File(uploadPath+filePath));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }

        return successResp(filePath);
    }

    @RequestMapping(value = "uploadFileWithRelativePath", method = RequestMethod.POST
            , headers = "content-type=multipart/form-data"
            , consumes = "multipart/*")
    @ApiOperation("文件上传（tomcat路径）接口")
    @ResponseBody
    public BaseResultVO uploadWithRelativePath(MultipartFile file){
        //组合保存地址
        String uploadPath = "";
        String uuid = "";
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(suffix.equalsIgnoreCase("mp4")){
            uuid = UUID.randomUUID().getMostSignificantBits()+".mp4";
            uploadPath = UploadVideoRelativePath;
        } else{
            uuid = UUID.randomUUID().getMostSignificantBits()+".jpg";
            uploadPath = UploadImgRelativePath;
        }
        File dirFile = new File(uploadPath );
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String fileName =file.getOriginalFilename();
        String filePath =fileName;

        try {
            //读取文件保存到具体目录中
            file.transferTo(new File(uploadPath + uuid));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
        Chapter chapter = new Chapter();
        chapter.setTitle(filePath);
        chapter.setVideoUrl(uuid);
        return successResp(chapter);
    }

    /**
     * 分片上传
     *
     * @return ResponseEntity<Void>
     */
    @PostMapping("/uploadVideo")
    @ResponseBody
    public String decrypt(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, Integer chunks, Integer chunk, String name, String guid) throws IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            if (file == null) {
                throw new RuntimeException("文件为空");
            }
            if (chunks == null && chunk == null) {
                chunk = 0;
            }
            File outFile = new File(decryptFilePathTemp + File.separator + guid, chunk + ".part");
            InputStream inputStream = file.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, outFile);
        }
        return "上传成功";
    }


    /**
     * 合并所有分片
     *
     * @throws Exception Exception
     */
    @PostMapping("/mergeVideo")
    @ResponseBody
    public BaseResultVO byteMergeAll(String guid, String fileName) throws Exception {
        System.out.println("merge:" + guid + "---" +fileName);
        File file = new File(decryptFilePathTemp + File.separator + guid);
        String uuid = UUID.randomUUID().getMostSignificantBits()+".mp4";
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                File partFile = new File(decryptFilePath + File.separator + uuid);
                for (int i = 0; i < files.length; i++) {
                    File s = new File(decryptFilePathTemp + File.separator + guid, i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(partFile, true);
                    FileUtils.copyFile(s, destTempfos);
                    destTempfos.close();
                }
                FileUtils.deleteDirectory(file);
            }

        }
        Chapter chapter = new Chapter();
        chapter.setTitle(fileName);
        chapter.setVideoUrl(uuid);
        return successResp(chapter);
    }

}
